package com.Glow.reggie.controller;

import com.Glow.reggie.common.R;
import com.Glow.reggie.dto.DishDto;
import com.Glow.reggie.entity.Category;
import com.Glow.reggie.entity.Dish;
import com.Glow.reggie.entity.DishFlavor;
import com.Glow.reggie.service.CategoryService;
import com.Glow.reggie.service.DishFlavorService;
import com.Glow.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author Glow
 * @Date 2022-08-01 13:03:28
 * @Description
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("dish")
public class DishController {
        @Autowired
        private DishService dishService;
        @Autowired
        private DishFlavorService dishFlavorService;
        @Autowired
        private CategoryService categoryService;
        @Autowired
        private RedisTemplate<Object,Object>redisTemplate;
        @PostMapping
        public R<String> save(@RequestBody DishDto dishDto)
        {
                log.info(dishDto.toString());
               dishService.saveDishWithDishFlavor(dishDto);
               //要删除redis内缓存的所属category分类的菜品
                Set keys = redisTemplate.keys("categoryId_*");
                 redisTemplate.delete(keys);
                return R.success("新增菜品成功");
        }
        @GetMapping
        @RequestMapping("page")
        public R<Page> page(int page,int pageSize,String name)
        {
                //分页构造器
                Page<Dish> pageInfo = new Page<>(page,pageSize);
                //要被粘贴的分页构造器DTo
                Page<DishDto> dishDtoPage = new Page<>();
                //分页条件构造器
                LambdaQueryWrapper<Dish>queryWrapper = new LambdaQueryWrapper<>();
                //添加过滤
                queryWrapper.like(name !=null,Dish::getName,name);
                queryWrapper.orderByDesc(Dish::getUpdateTime);
                dishService.page(pageInfo,queryWrapper);
                //因为普通的Dish分页没传过来分类名称category，所以还是要用到dishDto，因为已经查询过数据库，直接进行拷贝
                BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
                List<Dish> records = pageInfo.getRecords();
                List<DishDto> list
                = records.stream().map(item->{
                        DishDto dishDto = new DishDto();
                        //还要将当前item的值赋到dishDto中
                        BeanUtils.copyProperties(item,dishDto);
                        Long categoryId = item.getCategoryId();
                        Category category = categoryService.getById(categoryId);
                        if(category != null)
                        {
                                String categoryName = category.getName();
                                //实际上搞这么多就是为了将Dish分页查询到的内容将categoryName给填充罢了，但是这样做避免了多表查询，详情问百度多表查询
                                dishDto.setCategoryName(categoryName);
                        }
                        return dishDto;
                }).collect(Collectors.toList());
                dishDtoPage.setRecords(list);
                return R.success(dishDtoPage);
        }

        /**
         * 根据id查询菜品信息和对应的口味信息
         * @param id
         * @return
         */
        @GetMapping("{id}")
        public R<DishDto> get(@PathVariable Long id)
        {
                DishDto dishDto = dishService.getDishDtoByIdWithDishFlavor(id);
                return R.success(dishDto);
        }

        /**
         * 修改菜品
         * @param dishDto
         * @return
         */
        @PutMapping

        public R<String> update(@RequestBody DishDto dishDto)
        {
                log.info(dishDto.toString());
                dishService.updateDishWithDishFlavor(dishDto);
                //每次更新都要清除缓存
                Set keys = redisTemplate.keys("categoryId_*");
                redisTemplate.delete(keys);
                return R.success("新增菜品成功");
        }
//        @GetMapping("list")
//        public R<List<Dish>> list(Dish dish)
//        {
//                log.info(dish.getCategoryId().toString());
//                LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//                lambdaQueryWrapper.eq(null !=dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
//                lambdaQueryWrapper.eq(Dish::getStatus,1);
//                lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
//                List<Dish> list = dishService.list(lambdaQueryWrapper);
//                return R.success(list);
//        }
        @GetMapping("list")

        public R<List<DishDto>> list(Dish dish)
        {
                String categoryNames = "categoryId_"+dish.getCategoryId()+"_"+dish.getStatus();
                log.info(dish.getCategoryId().toString());
                List<DishDto> lists = (List<DishDto>) redisTemplate.opsForValue().get(categoryNames);
                //如果redis缓存了这个菜品ID，则不用再去查询数据库
                if(lists == null)
                {
                        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(null !=dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
                        lambdaQueryWrapper.eq(Dish::getStatus,1);
                        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
                        List<Dish> list = dishService.list(lambdaQueryWrapper);
                        List<DishDto>dishDtoList = list.stream().map((item->{
                                DishDto dishDto = new DishDto();
                                BeanUtils.copyProperties(item,dishDto);
                                Long DishId = item.getId();
                                LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(DishFlavor::getDishId,DishId);
                                dishDto.setFlavors(dishFlavorService.list(queryWrapper));
                                return dishDto;

                        })).collect(Collectors.toList());
                        redisTemplate.opsForValue().set(categoryNames,dishDtoList,60, TimeUnit.MINUTES);
                        return R.success(dishDtoList);
                }
                return R.success(lists);

        }
        @DeleteMapping
        public R<String> remove(String ids)
        {
                dishService.remove(ids);
                return R.success("修改成功！");
        }
        @PostMapping("status/{status}")
        public R<String> status(@PathVariable Integer status,String ids)
        {
                dishService.status(status,ids);
               return R.success("修改销售状态成功！");
        }
}
